<template>
    <div class="question-management">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>单选题管理</span>
            <div class="header-actions">
              <el-button type="primary" @click="addQuestion">
                <el-icon><Plus /></el-icon>
                添加题目
              </el-button>
              <el-button type="success" @click="exportQuestions">
                <el-icon><Download /></el-icon>
                导出题目
              </el-button>
              <el-button type="warning" @click="importDialogVisible = true">
                <el-icon><Upload /></el-icon>
                导入题目
              </el-button>
            </div>
          </div>
        </template>
        
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="filterForm" class="search-form">
          <el-form-item label="关键字">
            <el-input 
              v-model="filterForm.keyword" 
              placeholder="请输入题目内容" 
              clearable
            />
          </el-form-item>
          <el-form-item label="科目">
            <el-select 
              v-model="filterForm.subject" 
              placeholder="请选择科目" 
              clearable
            >
              <el-option label="科目一" value="1" />
              <el-option label="科目四" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度">
            <el-select 
              v-model="filterForm.difficulty" 
              placeholder="请选择难度" 
              clearable
            >
              <el-option label="简单" value="easy" />
              <el-option label="中等" value="medium" />
              <el-option label="困难" value="hard" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchQuestions">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 题目表格 -->
        <el-table
          :data="questions"
          border
          stripe
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" sortable />
          <el-table-column prop="content" label="题目内容" min-width="200" />
          <el-table-column prop="subject" label="科目" width="120">
            <template #default="{ row }">
              <el-tag :type="row.subject === '1' ? '' : 'danger'">
                {{ row.subject === '1' ? '科目一' : '科目四' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="120">
            <template #default="{ row }">
              <el-tag :type="getDifficultyTagType(row.difficulty)">
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="选项" width="200">
            <template #default="{ row }">
              <div v-for="(option, index) in row.options" :key="index" class="option-item">
                <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                <span class="option-content">{{ option }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="answer" label="正确答案" width="120">
            <template #default="{ row }">
              <el-tag type="success">{{ row.answer }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分值" width="80" sortable />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="text" 
                size="small" 
                @click="editQuestion(row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除该题目吗？"
                @confirm="deleteQuestion(row)"
              >
                <template #reference style="margin: 10px;" >
                  <el-button type="text" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
      
      <!-- 题目编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑单选题' : '添加单选题'"
        width="60%"
      >
        <el-form 
          :model="currentQuestion" 
          label-width="100px"
          :rules="rules"
          ref="questionForm"
        >
          <el-form-item label="题目内容" prop="content">
            <el-input 
              v-model="currentQuestion.content" 
              type="textarea" 
              :rows="3"
              placeholder="请输入题目内容"
            />
          </el-form-item>
          <el-form-item label="科目" prop="subject">
            <el-select 
              v-model="currentQuestion.subject" 
              placeholder="请选择科目"
            >
              <el-option label="科目一" value="1" />
              <el-option label="科目四" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度" prop="difficulty">
            <el-select 
              v-model="currentQuestion.difficulty" 
              placeholder="请选择难度"
            >
              <el-option label="简单" value="easy" />
              <el-option label="中等" value="medium" />
              <el-option label="困难" value="hard" />
            </el-select>
          </el-form-item>
          <el-form-item label="分值" prop="score">
            <el-input-number 
              v-model="currentQuestion.score" 
              :min="1" 
              :max="10"
            />
          </el-form-item>
          <el-form-item label="选项" prop="options">
            <div v-for="(option, index) in currentQuestion.options" :key="index" class="option-edit">
              <el-input 
                v-model="currentQuestion.options[index]"
                :placeholder="`选项 ${String.fromCharCode(65 + index)}`"
                style="width: 80%; margin-right: 10px;"
              />
              <el-button 
                type="danger" 
                plain 
                size="small" 
                @click="removeOption(index)"
                :disabled="currentQuestion.options.length <= 2"
              >
                删除
              </el-button>
            </div>
            <el-button 
              type="primary" 
              plain 
              size="small" 
              @click="addOption"
              style="margin-left: 10px;"
              :disabled="currentQuestion.options.length >= 6"
            >
              添加选项
            </el-button>
          </el-form-item>
          <el-form-item label="正确答案" prop="answer">
            <el-select 
              v-model="currentQuestion.answer" 
              placeholder="请选择正确答案"
            >
              <el-option
                v-for="(option, index) in currentQuestion.options"
                :key="index"
                :label="String.fromCharCode(65 + index)"
                :value="String.fromCharCode(65 + index)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="解析" prop="analysis">
            <el-input 
              v-model="currentQuestion.analysis" 
              type="textarea" 
              :rows="3"
              placeholder="请输入题目解析"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveQuestion">保存</el-button>
        </template>
      </el-dialog>
      
      <!-- 导入题目对话框 -->
      <el-dialog
        v-model="importDialogVisible"
        title="导入单选题"
        width="40%"
      >
        <el-upload
          class="upload-demo"
          drag
          action=""
          :auto-upload="false"
          :on-change="handleFileChange"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传Excel文件，支持.xlsx和.xls格式
            </div>
          </template>
        </el-upload>
        
        <template #footer>
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="importQuestions">导入</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, reactive } from 'vue'
  import { Plus, Download, Upload, Search, Refresh } from '@element-plus/icons-vue'
  
  export default {
    name: 'SingleChoiceManagement',
    components: {
      Plus, Download, Upload, Search, Refresh
    },
    setup() {
      // 搜索表单
      const filterForm = reactive({
        keyword: '',
        subject: '',
        difficulty: ''
      })
      
      // 题目数据
      const questions = ref([
        {
          id: 1,
          content: '驾驶机动车在道路上违反道路交通安全法的行为，属于什么行为？',
          subject: '1',
          difficulty: 'easy',
          options: ['违章行为', '违法行为', '过失行为', '违规行为'],
          answer: 'B',
          score: 1,
          analysis: '根据《道路交通安全法》第二条规定，违反道路交通安全法的行为属于违法行为。'
        },
        {
          id: 2,
          content: '机动车驾驶人初次申领驾驶证后的实习期是多长时间？',
          subject: '1',
          difficulty: 'medium',
          options: ['6个月', '12个月', '18个月', '24个月'],
          answer: 'B',
          score: 1,
          analysis: '根据《机动车驾驶证申领和使用规定》第七十四条，机动车驾驶人初次申领驾驶证后的实习期为12个月。'
        }
      ])
      
      // 分页
      const pagination = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 0
      })
      
      // 加载状态
      const loading = ref(false)
      
      // 当前编辑的题目
      const currentQuestion = ref({
        id: null,
        content: '',
        subject: '1',
        difficulty: 'easy',
        options: ['', '', '', ''],
        answer: '',
        score: 1,
        analysis: ''
      })
      
      // 对话框状态
      const dialogVisible = ref(false)
      const isEditMode = ref(false)
      const importDialogVisible = ref(false)
      
      // 表单验证规则
      const rules = reactive({
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '请选择科目', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        options: [
          { 
            validator: (rule, value, callback) => {
              if (value.some(option => !option.trim())) {
                callback(new Error('所有选项不能为空'))
              } else if (new Set(value.map(opt => opt.trim())).size !== value.length) {
                callback(new Error('选项内容不能重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        answer: [
          { required: true, message: '请选择正确答案', trigger: 'change' }
        ],
        score: [
          { required: true, message: '请设置分值', trigger: 'blur' }
        ]
      })
      
      // 获取难度标签类型
      const getDifficultyTagType = (difficulty) => {
        const map = {
          easy: 'success',
          medium: 'warning',
          hard: 'danger'
        }
        return map[difficulty] || ''
      }
      
      // 获取难度文本
      const getDifficultyText = (difficulty) => {
        const map = {
          easy: '简单',
          medium: '中等',
          hard: '困难'
        }
        return map[difficulty] || difficulty
      }
      
      // 搜索题目
      const searchQuestions = () => {
        loading.value = true
        // 模拟搜索
        setTimeout(() => {
          loading.value = false
        }, 500)
      }
      
      // 重置搜索
      const resetFilter = () => {
        Object.assign(filterForm, {
          keyword: '',
          subject: '',
          difficulty: ''
        })
        searchQuestions()
      }
      
      // 添加题目
      const addQuestion = () => {
        currentQuestion.value = {
          id: null,
          content: '',
          subject: '1',
          difficulty: 'easy',
          options: ['', '', '', ''],
          answer: '',
          score: 1,
          analysis: ''
        }
        isEditMode.value = false
        dialogVisible.value = true
      }
      
      // 编辑题目
      const editQuestion = (question) => {
        currentQuestion.value = { ...question }
        isEditMode.value = true
        dialogVisible.value = true
      }
      
      // 删除题目
      const deleteQuestion = (question) => {
        const index = questions.value.findIndex(q => q.id === question.id)
        if (index !== -1) {
          questions.value.splice(index, 1)
        }
      }
      
      // 保存题目
      const saveQuestion = () => {
        // 在实际应用中，这里应该调用API保存数据
        if (isEditMode.value) {
          const index = questions.value.findIndex(q => q.id === currentQuestion.value.id)
          if (index !== -1) {
            questions.value.splice(index, 1, currentQuestion.value)
          }
        } else {
          currentQuestion.value.id = questions.value.length + 1
          questions.value.push(currentQuestion.value)
        }
        dialogVisible.value = false
      }
      
      // 处理选中行
      const handleSelectionChange = (selection) => {
        console.log('选中行:', selection)
      }
      
      // 分页变化
      const handlePageChange = (page) => {
        pagination.currentPage = page
        // 在实际应用中，这里应该调用API获取对应页的数据
      }
      
      // 每页条数变化
      const handleSizeChange = (size) => {
        pagination.pageSize = size
        // 在实际应用中，这里应该调用API获取数据
      }
      
      // 导出题目
      const exportQuestions = () => {
        console.log('导出题目')
      }
      
      // 处理文件上传
      const handleFileChange = (file) => {
        console.log('上传文件:', file)
      }
      
      // 导入题目
      const importQuestions = () => {
        console.log('导入题目')
        importDialogVisible.value = false
      }
      
      // 添加选项
      const addOption = () => {
        currentQuestion.value.options.push('')
      }
      
      // 删除选项
      const removeOption = (index) => {
        currentQuestion.value.options.splice(index, 1)
        // 如果删除的是正确答案，清空答案
        if (currentQuestion.value.answer === String.fromCharCode(65 + index)) {
          currentQuestion.value.answer = ''
        }
      }
      
      return {
        filterForm,
        questions,
        pagination,
        loading,
        currentQuestion,
        dialogVisible,
        isEditMode,
        importDialogVisible,
        rules,
        getDifficultyTagType,
        getDifficultyText,
        searchQuestions,
        resetFilter,
        addQuestion,
        editQuestion,
        deleteQuestion,
        saveQuestion,
        handleSelectionChange,
        handlePageChange,
        handleSizeChange,
        exportQuestions,
        handleFileChange,
        importQuestions,
        addOption,
        removeOption
      }
    }
  }
  </script>
  
  <style scoped>
  .question-management {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .option-item {
    margin-bottom: 5px;
    display: flex;
  }
  
  .option-label {
    font-weight: bold;
    margin-right: 5px;
  }
  
  .option-content {
    flex: 1;
  }
  
  .option-edit {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .upload-demo {
    text-align: center;
  }
  </style>